/**
 * 日志管理与埋点功能
 * 支持多级别日志、错误上报、行为埋点
 */

import { getCurrentConfig } from './config.js'
import { post } from '../services/request.js'

// 日志级别
const LOG_LEVELS = {
  DEBUG: 0,
  INFO: 1,
  WARN: 2,
  ERROR: 3
}

// 当前日志级别（生产环境建议 INFO 以上）
const CURRENT_LOG_LEVEL = LOG_LEVELS.INFO

class Logger {
  constructor() {
    this.sessionId = this.generateSessionId()
    this.logs = []
    this.maxLogs = 100 // 最大本地日志数量
    this.isEnabled = true
    this.userInfo = null
    
    // 从存储恢复设置
    this.loadSettings()
    
    // 监听应用生命周期
    this.bindLifecycle()
  }

  /**
   * 生成会话ID
   */
  generateSessionId() {
    return `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  }

  /**
   * 设置用户信息
   */
  setUser(userInfo) {
    this.userInfo = userInfo
  }

  /**
   * 开启/关闭日志
   */
  setEnabled(enabled) {
    this.isEnabled = enabled
    uni.setStorageSync('logger_enabled', enabled)
  }

  /**
   * 加载设置
   */
  loadSettings() {
    try {
      const enabled = uni.getStorageSync('logger_enabled')
      if (enabled !== null && enabled !== undefined) {
        this.isEnabled = enabled
      }
    } catch (error) {
      console.warn('加载日志设置失败:', error)
    }
  }

  /**
   * 通用日志方法
   */
  log(level, message, data = null) {
    if (!this.isEnabled || level < CURRENT_LOG_LEVEL) {
      return
    }

    const logEntry = {
      id: this.generateLogId(),
      level: Object.keys(LOG_LEVELS)[level],
      message,
      data,
      timestamp: new Date().toISOString(),
      sessionId: this.sessionId,
      userId: this.userInfo?.id || 'anonymous',
      page: this.getCurrentPage(),
      userAgent: this.getUserAgent()
    }

    // 添加到本地日志队列
    this.addToQueue(logEntry)

    // 控制台输出
    this.consoleOutput(logEntry)

    // 错误级别立即上报
    if (level === LOG_LEVELS.ERROR) {
      this.reportError(logEntry)
    }
  }

  /**
   * 调试日志
   */
  debug(message, data) {
    this.log(LOG_LEVELS.DEBUG, message, data)
  }

  /**
   * 信息日志
   */
  info(message, data) {
    this.log(LOG_LEVELS.INFO, message, data)
  }

  /**
   * 警告日志
   */
  warn(message, data) {
    this.log(LOG_LEVELS.WARN, message, data)
  }

  /**
   * 错误日志
   */
  error(message, error) {
    let errorData = null
    
    if (error instanceof Error) {
      errorData = {
        name: error.name,
        message: error.message,
        stack: error.stack
      }
    } else if (typeof error === 'object') {
      errorData = error
    } else {
      errorData = { detail: error }
    }

    this.log(LOG_LEVELS.ERROR, message, errorData)
  }

  /**
   * 行为埋点
   */
  track(event, properties = {}) {
    if (!this.isEnabled) return

    const trackData = {
      event,
      properties: {
        ...properties,
        timestamp: Date.now(),
        sessionId: this.sessionId,
        userId: this.userInfo?.id || 'anonymous',
        page: this.getCurrentPage(),
        ...this.getDeviceInfo()
      }
    }

    // 记录到日志
    this.info(`[埋点] ${event}`, trackData)

    // 上报埋点数据
    this.reportTrack(trackData)
  }

  /**
   * 页面访问埋点
   */
  trackPageView(pagePath, referrer = '') {
    this.track('page_view', {
      page_path: pagePath,
      referrer: referrer,
      visit_time: Date.now()
    })
  }

  /**
   * 用户行为埋点
   */
  trackUserAction(action, target, extra = {}) {
    this.track('user_action', {
      action,
      target,
      ...extra
    })
  }

  /**
   * 性能监控
   */
  trackPerformance(metric, value, extra = {}) {
    this.track('performance', {
      metric,
      value,
      ...extra
    })
  }

  /**
   * 业务事件埋点
   */
  trackBusiness(eventName, data = {}) {
    this.track('business', {
      event_name: eventName,
      ...data
    })
  }

  /**
   * 添加到日志队列
   */
  addToQueue(logEntry) {
    this.logs.push(logEntry)
    
    // 超过最大数量时移除最老的日志
    if (this.logs.length > this.maxLogs) {
      this.logs.shift()
    }
  }

  /**
   * 控制台输出
   */
  consoleOutput(logEntry) {
    const { level, message, data } = logEntry
    const prefix = `[${logEntry.timestamp}] [${level}]`
    
    switch (level) {
      case 'DEBUG':
        console.debug(prefix, message, data)
        break
      case 'INFO':
        console.info(prefix, message, data)
        break
      case 'WARN':
        console.warn(prefix, message, data)
        break
      case 'ERROR':
        console.error(prefix, message, data)
        break
    }
  }

  /**
   * 上报错误
   */
  async reportError(logEntry) {
    try {
      await post('/v1/logs/error', {
        log: logEntry,
        device_info: this.getDeviceInfo(),
        app_info: this.getAppInfo()
      }, {
        showLoading: false,
        preventDuplicate: false
      })
    } catch (error) {
      console.warn('错误上报失败:', error)
    }
  }

  /**
   * 上报埋点
   */
  async reportTrack(trackData) {
    try {
      await post('/v1/analytics/track', trackData, {
        showLoading: false,
        preventDuplicate: false
      })
    } catch (error) {
      console.warn('埋点上报失败:', error)
    }
  }

  /**
   * 批量上报日志
   */
  async flushLogs() {
    if (this.logs.length === 0) return

    try {
      const logsToReport = [...this.logs]
      this.logs = []

      await post('/v1/logs/batch', {
        logs: logsToReport,
        device_info: this.getDeviceInfo(),
        app_info: this.getAppInfo()
      }, {
        showLoading: false,
        preventDuplicate: false
      })

      console.log(`上报 ${logsToReport.length} 条日志`)
    } catch (error) {
      console.warn('批量上报日志失败:', error)
      // 上报失败时恢复日志（避免丢失）
      this.logs = [...error.logs, ...this.logs].slice(0, this.maxLogs)
    }
  }

  /**
   * 获取当前页面
   */
  getCurrentPage() {
    try {
      const pages = getCurrentPages()
      if (pages.length > 0) {
        const currentPage = pages[pages.length - 1]
        return currentPage.route || ''
      }
    } catch (error) {
      // 忽略错误
    }
    return 'unknown'
  }

  /**
   * 获取设备信息
   */
  getDeviceInfo() {
    try {
      const systemInfo = uni.getSystemInfoSync()
      return {
        platform: systemInfo.platform,
        system: systemInfo.system,
        model: systemInfo.model,
        brand: systemInfo.brand,
        screenWidth: systemInfo.screenWidth,
        screenHeight: systemInfo.screenHeight,
        pixelRatio: systemInfo.pixelRatio,
        language: systemInfo.language,
        version: systemInfo.version,
        SDKVersion: systemInfo.SDKVersion
      }
    } catch (error) {
      return {}
    }
  }

  /**
   * 获取应用信息
   */
  getAppInfo() {
    return {
      version: '1.0.0', // 应用版本
      build: '1',       // 构建号
      environment: getCurrentConfig().ENV_MODE
    }
  }

  /**
   * 获取用户代理字符串
   */
  getUserAgent() {
    try {
      const systemInfo = uni.getSystemInfoSync()
      return `${systemInfo.platform}/${systemInfo.system}`
    } catch (error) {
      return 'unknown'
    }
  }

  /**
   * 生成日志ID
   */
  generateLogId() {
    return `log_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  }

  /**
   * 绑定生命周期
   */
  bindLifecycle() {
    // 应用隐藏时上报日志
    uni.onAppHide(() => {
      this.flushLogs()
    })

    // 应用错误监听
    uni.onError((error) => {
      this.error('应用异常', error)
    })

    // 页面未找到
    uni.onPageNotFound((res) => {
      this.error('页面未找到', {
        path: res.path,
        query: res.query,
        isEntryPage: res.isEntryPage
      })
    })
  }

  /**
   * 导出日志（用于调试）
   */
  exportLogs() {
    return {
      sessionId: this.sessionId,
      logs: this.logs,
      userInfo: this.userInfo,
      settings: {
        isEnabled: this.isEnabled,
        logLevel: CURRENT_LOG_LEVEL
      }
    }
  }

  /**
   * 清空日志
   */
  clearLogs() {
    this.logs = []
    console.log('本地日志已清空')
  }
}

// 创建全局实例
const logger = new Logger()

// 便捷方法
export const debug = (message, data) => logger.debug(message, data)
export const info = (message, data) => logger.info(message, data)
export const warn = (message, data) => logger.warn(message, data)
export const error = (message, err) => logger.error(message, err)
export const track = (event, properties) => logger.track(event, properties)
export const trackPageView = (path, referrer) => logger.trackPageView(path, referrer)
export const trackUserAction = (action, target, extra) => logger.trackUserAction(action, target, extra)
export const trackPerformance = (metric, value, extra) => logger.trackPerformance(metric, value, extra)
export const trackBusiness = (eventName, data) => logger.trackBusiness(eventName, data)

// 导出实例和类
export default logger
export { Logger, LOG_LEVELS }